package atlantik.ui;

import static java.lang.Math.max;
import static java.lang.Math.min;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.Rectangle2D;

import javax.swing.JComponent;

import atlantik.game.Atlantik;
import atlantik.game.Player;

public class TokenView extends JComponent  {

	private static final long serialVersionUID = 6009335074727417445L;

	private static final Dimension SMALLEST = new Dimension(0, 0);

	private final Player item;
	
	public TokenView(Atlantik client, Player item) {
		this.item = item;
		setOpaque(false);
	}

	public Dimension getMaximumSize() {
		updateToken();
		return realSize;
	}

	public Dimension getPreferredSize() {
		return SMALLEST;
	}

	public void paintComponent(Graphics gr) {
		Graphics2D g = (Graphics2D) gr;

		updateToken();
		if( realSize == null )
			return;
		int x = (getWidth() - realSize.width) / 2;
		int y = (getHeight() - realSize.height - (int)nameBounds.getHeight()) / 2;
		if( scaledToken == null )
			return;
		g.drawImage(scaledToken, x, y, this);
		
		if( nameBounds == null )
			return;
		x = (getWidth() - (int)nameBounds.getWidth()) / 2;
		y += realSize.height;
		g.setColor(Color.GRAY);
		g.fillRect(x, y, (int)nameBounds.getWidth(), (int)nameBounds.getHeight());
		
		if( name == null )
			return;
		g.setColor(Color.WHITE);
		g.drawString(name, x, y + g.getFontMetrics().getMaxAscent());
	}
	
	private double lastScale = 0;
	private Image token;
	private Dimension tokenSize;
	private String name;
	private Rectangle2D nameBounds;
	private Dimension realSize;
	private Image scaledToken;
	private void updateToken() {
		if( token != item.getToken() ) {
			token = item.getToken();
			tokenSize = new Dimension(token.getWidth(this), token.getHeight(this));
		}
		if( !item.getName().equals(name) ) {
			name = item.getName();
			nameBounds = getFontMetrics(getFont()).getStringBounds(name, getGraphics());
		}

		Dimension componentSize = getSize();
		if( componentSize.width == 0 || componentSize.height == 0 )
			return;
		
		if( tokenSize.width == 0 || tokenSize.height == 0 )
			return;
		
		double scale = min(
				(double)componentSize.width / max(tokenSize.width, (int)nameBounds.getWidth()),
				(double)componentSize.height / (tokenSize.height + nameBounds.getHeight()) );
		if( scale == lastScale )
			return;
		
		Dimension newSize = new Dimension((int)((double)tokenSize.width * scale), (int)((double)tokenSize.height * scale));
		if( newSize.width == 0 || newSize.height == 0 )
			return;
		realSize = newSize;
		scaledToken = token.getScaledInstance(realSize.width, realSize.height, Image.SCALE_SMOOTH);
		lastScale = scale;
	}

}
